The following sections cover some of the basics of
scripting with PowerShell. We hope this information will help you
understand how you can use PowerShell in various situations to automate
various tasks.
A Few Basic Cmdlets
Following is a list of a few basic cmdlets and how they can be used, with a brief example:
Get-ChildItem (aka dir, gci)—
Cmdlet used to list child items in a provider. Mostly used to list
things such as files and directories in a file system. Example: Get-ChildItem *.ps1
Select-Object— Cmdlet used to retrieve only specific properties. See Get-Help Select-Object –Examples for examples.
Group-Object— Cmdlet used to group objects based on their properties. See Get-Help Group-Object –Examples for examples.
Sort-Object— Cmdlet used to sort objects based on their properties. See Get-Help Sort-Object –Examples for examples.
Read-Host— Cmdlet used to read input from the screen, usually from a user, before continuing. Example: Read-Host "Enter a database name".
Measure-Command— Cmdlet used to measure how much time a particular scriptblock took to run. Example: Measure-Command {Get-Command}.
Write-Host— Cmdlet used to basically display output to the console. This cmdlet was covered earlier.
New-Object— Cmdlet used to create an instance of a .NET (or COM) object. Examples are provided later.
Get-Alias— Cmdlet used to get a listing of the aliases on the system. Get-Alias, with no arguments, lists all the aliases configured on the local system.
Get-Content— Cmdlet used to read the contents of a file. Typically, only text-based files are supported. Example: Get-Content my_script.ps1.
Add-Content— Cmdlet used to add or append content to a file. Example: Add-Content my_file.txt "testing".
Set-Content— Cmdlet used to set the contents of a file (it overwrites any existing content). Example: Set-Content my_file.txt "testing 123".
Start-Transcript— Cmdlet used also with Stop-Transcript to record everything in the console to a specific text file. Example: Start-Transcript.
Creating a PowerShell Script
Creating a PowerShell script is as simple as placing a few commands into a .ps1 script and then invoking that script. Here’s a simple example of putting the Write-Host cmdlet into a script and then running it.
PS> add-content c:\temp\test.ps1 "Write-Host `testing`"
PS>c:\temp\test.ps1
testing
PS>
In the preceding example, a Write-Host cmdlet was placed in a file named test.ps1, and then the file was invoked. The output resulted in the string "testing" being output to the script. Notepad or any other simple text editor could also be used to create more complicated scripts.
Adding Comments
Adding comments to a PowerShell script is as simple as adding the # character at the beginning of the line. To comment out entire blocks of code, you must use a # on each line.
Note
Another way to comment out blocks of code is to use something called a here string.
Variables
A very useful feature of PowerShell,
and thus of SQL-PowerShell, is the ability to place objects into a
variable. This allows you to run any kind of command and place any
objects produced into a variable for later use.
A string can be easily saved as a variable:
PS>$var="AdventureWorks2008R2"
PS>$var
AdventureWorks2008R2
In the preceding example, the string is saved as the variable $var and then output to the script when the variable is simply invoked:
PS>$database=read-host "Enter a database name"
Enter a database name:AdventureWorks2008R2
PS>$database
AdventureWorks2008R2
The Read-Host cmdlet was introduced briefly already. In this example, the Read-Host cmdlet is used to read input from the console, and the information input is passed to the $database variable.
Note
When you perform certain
actions in a script, a function, and even from the command line, the
scope assigned to the variable or function determines how this variable
will be seen by other scripts, functions, and so on. The details of
scoping are not discussed any further, but it is still an important
concept to remember as you use PowerShell more and more.
Note
You can issue the Get-Help about_shell_variable and Get-Help about_scope commands in Powershell for more information and examples about shell variables.
Escaping Characters
Often a special character may be
used—for example, in DOS commands—but PowerShell tries to interpret it
differently. Let’s consider the dollar sign character ($). PowerShell normally tries to interpret it as a variable:
PS C:\> $var="$5 discount"
PS C:\> $var
discount
PS C:\> $var="`$5 discount"
PS C:\> $var
$5 discount
PS C:\>
The preceding example shows how
the escape character, which is the backtick (`), is used to escape the
dollar sign, so that PowerShell doesn’t try to interpret the character
literally as the beginning of a variable.
Note
You can execute the Get-Help about_escape_character command in PowerShell for more information and examples.
Special Variable $_
In PowerShell, $_
is a special variable that represents the current object in the
pipeline. When several cmdlets are piped together, this special variable
may be used often.
Note
A special variable named $input also represents objects passed along the pipeline.
Note
See Get-Help about_automatic_variables for more information and examples.
Joining Variables and Strings
The concept of objects was
already introduced briefly. When you are dealing with simple strings,
you can easily concatenate them together using the plus (+) sign to
create a new string:
PS>$last_name="Doe"
PS>$first_name="John"
PS>$full_name=$last_name+", "+$first_name
PS>$full_name
Doe, John
PS>
In this example, two variables
containing simple strings are defined, and they are simply concatenated
together to create a third variable, which is then displayed to the
console.
Note
This kind of
concatenation works when both variables are strings. An error may be
returned if the variable is of another data type.
An example is provided later with the AdventureWorks2008R2 database where string variables from two different columns in the same table will be joined together using this feature.
Passing Arguments
PowerShell has a special reserved variable named $args.
It can be used with scripts and functions, and represents any arguments
passed to the script or function when it is invoked, as shown here:
PS>add-content c:\temp\parameter.ps1 "`$args.count"
PS>add-content c:\temp\parameter.ps1 "`$args[0]"
PS>c:\temp\parameter.ps1 1 2 3
3
1
PS>
In the preceding example, a two-line script is created, and then it is invoked while passing some arguments to it. $args.count displays the number of arguments passed to the script, whereas $args[0] displays the value of the first argument only.
Later, an example of a
PowerShell script that can do a database backup is provided. The example
is extended to show how a script could be used to accept an argument
that would be the name of the database the script will back up.
Using Param
A special construct, param, can be used to force the way arguments are passed to a script or function:
PS>function test_param {
>> param([string]$arg1)
>> write-host "Argument 1 is $arg1"
>> }
>>PS>test_param "testing"
Argument 1 is testing
PS>test_param -arg1 "testing"
Argument 1 is testing
PS>
In this example, param is used to specify that a parameter passed to this script will be a string object and will be contained in the variable $arg1 for later use in the script.
Note
The biggest difference between using param or $args with arguments occurs when the number of arguments is known versus unknown. The param keyword should not be used when the number of arguments passed is not known.
Note
[string]
is a shortcut in PowerShell where you specify that the argument, as in
the preceding example, will be a string, and not something else such as a
number or integer. A dozen or so of these shortcuts are available in
PowerShell, and they are typically known as type accelerators.
Arrays
To PowerShell, arrays are simply a listing of data. They can be used for various tasks and can be created easily, as you can see here:
PS>$var="foo","bar"
PS>$var
foo
bar
PS>
In this example, an array is
created with two values, and then it is simply invoked, which simply
results in outputting each element of the array, one per line. When an
array is created, a reference can be made to a particular element of the
array using a special “[]” syntax, like this:
Note
The first element of an array
is the element zero; therefore, the first record in an array is
retrieved by referencing the element id [0].
The count property is also useful as a property of array objects (remember that everything n PowerShell is a .NET object:
The count property is used to iterate through each element of an array.
Note
Arrays can also be defined in at least two other ways: with a type accelerator ([array]$var is an example) or using a notation like this:
Note
You can execute the Get-Help about_array command for more information and examples on using arrays in PowerShell.
In a later example, this feature of retrieving a particular element of an array is used with the AdventureWorks2008R2 database.
Operators
A task commonly performed
both from the console and also in scripts is to compare two strings
against each other. The most common operators are as follows:
Arithmetic— When comparing numbers or integers, for example:
Comparison— When comparing strings, for example:
In both of these cases, a Boolean value is returned (True or False).
Note
Execute the Get-Help about_operator command for more information and examples.